package com.qk.Interceptor;

import com.qk.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求路径
        //2、判断请求路径是否是登录路径如果是放行
        String uri = request.getRequestURI();
        if(uri.contains("/login")){
            log.info("登录请求：{}", uri);

            return true;
        }
        //3、获取请求头中的token
        String token = request.getHeader("token");

        //4、判断token是否存在，不存在响应401状态码
        if(token == null || token.equals("")){
            log.info("请求头token为空");
            response.setStatus(401);
            return false;
        }

        //5、存在则解析token，判断是否合法，不合法响应401状态码
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("token不合法");
            response.setStatus(401);
            return false;
        }
        //6、合法则放行
        return true;
    }
}
